/* 
 * File:   Protocol.cpp
 * Author: Saulio
 * Created on April 16, 2012, 4:27 PM
 */

#include "Quimera_protocol_v1.h"

static bool interrupt=false;
int Message_queue_setup(const int & queue_key)
{
    int id_message_queue;
    key_t key; 
    key = ftok ("/bin/ls", queue_key);
	if (key == (key_t)-1)
	{
		std::cout << "Error al obtener clave para cola mensajes" << std::endl;
		return(EXIT_FAILURE);
	} 
    
        id_message_queue = msgget (key, 0600 | IPC_CREAT);
	if (id_message_queue == -1)
	{
		std::cout << "Error al obtener identificador para cola mensajes" << std::endl;
		return(EXIT_FAILURE);
	}
        
    return (id_message_queue);
}

int main(int argc, char** argv)
{   
    unsigned char               domain;
    unsigned int                first_pool;
    unsigned int                last_pool;
    int                         packer_queue_id;
    int                         unpacker_queue_id;
    
    message_queue outbound_mail;
    domain=unsigned(char(atoi(argv[2])));
    first_pool=atoi(argv[3]);
    last_pool=atoi(argv[4]);
    
    bzero((char *) &outbound_mail, sizeof(outbound_mail));
    packer_queue_id=Message_queue_setup(S_PACKER_QUEUE_KEY);
    unpacker_queue_id=Message_queue_setup(S_UNPACKER_QUEUE_KEY);
    
    std::cout<<"packer_queue_id: "<< packer_queue_id << std::endl;
    std::cout<<"unpacker_queue_id: "<< unpacker_queue_id << std::endl;
    
    Quimera_server serv(domain,first_pool,last_pool,packer_queue_id);
    std::cout<<"Ready, esperando por clientes: "<<std::endl;
      
         while(!interrupt){
             
             sleep(1);
             if(msgrcv(unpacker_queue_id, (struct msgbuf *)&outbound_mail,
             sizeof(outbound_mail.package)+sizeof(outbound_mail.cli_addr),HIGHT_PRIORITY,IPC_NOWAIT)>0)
             {
               std::cout<<"Mensaje de alta prioridad"<<std::endl;
               serv.Package_processor(outbound_mail);
             }
         
             else if(msgrcv(unpacker_queue_id, (struct msgbuf *)&outbound_mail,
             sizeof(outbound_mail.package)+sizeof(outbound_mail.cli_addr),MEDIUM_PRIORITY,IPC_NOWAIT)>0)
             {
               std::cout<<"Mensaje de media prioridad"<<std::endl;
               serv.Package_processor(outbound_mail);  
             }
         
             else if(msgrcv(unpacker_queue_id, (struct msgbuf *)&outbound_mail,
             sizeof(outbound_mail.package)+sizeof(outbound_mail.cli_addr),LOW_PRIORITY,IPC_NOWAIT)>0)
             {
               std::cout<<"Mensaje de baja prioridad"<<std::endl;
               serv.Package_processor(outbound_mail);  
             }
           
             if(outbound_mail.id_message==CLR)
             {
                 interrupt=true;
                 
             
             }   
         }
msgctl (unpacker_queue_id, IPC_RMID, (struct msqid_ds *)NULL);
return 0;
}